package com.lanou.bbs.dao;

import com.lanou.bbs.entity.User;
import com.lanou.bbs.util.JDBCUtil;
import com.lanou.bbs.util.MyResultSet;
import com.lanou.bbs.util.MyStatement;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


@Repository
public class UserDao {

//    public User login(String username) {
//        String sql = "select * from users where username = ?;";
//        MyStatement statement = JDBCUtil.getStatement(sql);
//        statement.setString(1, username);
//        MyResultSet rs = statement.executeQuery();
//        if (rs.next()) {
//           User user = new User();
//            user.setUid(rs.getInt("uid"))
//                    .setUsername(rs.getString("username"))
//                    .setPwd(rs.getString("pwd"))
//                    .setGender(rs.getString("gender"))
//                    .setNickname(rs.getString("nickname"));
//            return user;
//        } else {
//            return null;
//        }
//    }

    public User myLogin(User user) throws SQLException {
        String sql = "select * from users where username = ? and pwd = ?";
        Connection conn = JDBCUtil.getConn();
        PreparedStatement statement = conn.prepareStatement(sql);
        statement.setString(1,user.getUsername());
        statement.setString(2,user.getPwd());
        ResultSet resultSet = statement.executeQuery();
        User user1 = null;
        if (resultSet.next()) {
            user1 =  new User();
            user1.setUsername(resultSet.getString("username"));
            user1.setPwd(resultSet.getString("pwd"));

        }
        return user1;
    }

    public boolean hasUsername(String username) {
        String sql = "select count(username) from users where username = ?";
        MyStatement statement = JDBCUtil.getStatement(sql);
        statement.setString(1, username);
        MyResultSet rs = statement.executeQuery();
        if (rs.next()) {
            return rs.getInt(1) > 0;
        }
        return false;
    }

    public boolean register(User user) {
        try {
            String sql = "insert into users (username, pwd, gender, nickname) values (?, ?, ?, ?)";
            MyStatement statement = JDBCUtil.getStatement(sql);
            statement.setString(1, user.getUsername());
            statement.setString(2, user.getPwd());
            statement.setString(3, user.getGender());
            statement.setString(4, user.getNickname());
            int i = statement.executeUpdate();
            return i > 0;
        } catch (Exception e) {
            try {
                JDBCUtil.getConn().rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
        return false;
    }
}
